{% extends 'base.html' %}
{% load static %}
{% block title %}{{ idc.name }} - 3D视图 - 机房监控{% endblock %}
{% block extra_css %}
<style>
        /* 移除可能影响下拉菜单的全局样式 */
        *{
            margin:0;
            padding:0;
            text-decoration: none;
            box-sizing: border-box;
        }
        ul,li{
            list-style: none;
            border:none;
        }
        .clear:after{
            content:"";
            display:block;
            clear:both;
        }
        body{
            overflow: hidden;
        }
        
        /* 修改设备选择窗口和下拉菜单的样式 */
        .device-modal select {
            position: relative !important; 
            z-index: 9999 !important;  /* 提高z-index */
            -webkit-appearance: menulist !important;
            -moz-appearance: menulist !important;
            appearance: menulist !important;
            background-color: #fff !important;
            border: 1px solid #ddd !important;
            cursor: pointer !important;
            pointer-events: auto !important;
            display: block !important;
            width: 100% !important;
            height: 32px !important;
            padding: 5px !important;
            font-size: 14px !important;
            color: #333 !important;
            border-radius: 3px !important;
        }
        
        /* 确保下拉菜单选项可见 */
        .device-modal select option {
            position: relative !important;
            z-index: 9999 !important;  /* 提高z-index */
            display: block !important;
            padding: 8px !important;
            background-color: #fff !important;
            color: #333 !important;
            font-size: 14px !important;
        }
        
        /* 确保设备选择窗口正确定位和层级 */
        .device-modal {
            position: fixed !important;
            z-index: 9998 !important;  /* 提高z-index */
            background-color: #fff !important;
            pointer-events: auto !important;
            overflow: visible !important;
        }
        
        /* 确保表单组不会遮挡下拉菜单 */
        .device-modal .form-group {
            position: relative !important;
            z-index: 9998 !important;  /* 提高z-index */
            margin-bottom: 15px !important;
            pointer-events: auto !important;
        }
        
        /* 添加设备图标样式 */
        .add-device-icon {
            position: fixed;
            left: 20px;
            top: 20px;
            width: 40px;
            height: 40px;
            background-color: #fff;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            z-index: 1000;
        }
        
        /* 设备选择窗口样式 */
        .device-modal {
            display: none;
            position: fixed;
            left: 70px;
            top: 20px;
            width: 227px;
            height: 376px;
            background-color: #fff;
            border-radius: 4px;
            padding: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 1000;
            overflow: visible;  /* 允许下拉菜单超出容器 */
        }
        
        .device-modal .form-group {
            margin-bottom: 15px;
            position: relative;
            z-index: 1000;
        }
        
        .device-modal label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }
        
        .device-modal .btn-group {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }
        
        .device-modal button {
            padding: 5px 15px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .device-modal .save-btn {
            background-color: #4CAF50;
            color: white;
        }
        
        .device-modal .cancel-btn {
            background-color: #f44336;
            color: white;
        }
        
        /* 添加下拉菜单hover效果 */
        .device-modal select:hover {
            border-color: #999;
        }
        
        /* 添加下拉菜单focus效果 */
        .device-modal select:focus {
            border-color: #666;
            outline: none;
        }
        
        /* 确保选项hover效果 */
        .device-modal select option:hover {
            background-color: #f5f5f5;
        }


</style>
{% endblock %}
{% block content %}


<!-- 添加设备图标 -->
<div class="add-device-icon">
    <i>+</i>
</div>

<!-- 设备选择窗口 -->
<div class="device-modal">
    <div class="form-group">
        <label for="deviceType">设备类型</label>
        <select id="deviceType"  tabindex="1">
        </select>
    </div>
    <div class="form-group">
        <label for="deviceList">设备</label>
        <select id="deviceList" name="deviceList" tabindex="2">
               
        </select>
    </div>
    <div class="form-group">
        <label>存放机柜</label>
        <select id="cabinetList"></select>
    </div>
    <div class="form-group">
        <label>选择U位</label>
        <select id="uPosition"></select>
    </div>
    <div class="btn-group">
        <button class="save-btn">保存</button>
        <button class="cancel-btn">取消</button>
    </div>
</div>
{% endblock %}

{% block extra_js %}

<!--    <script src="js/jquery-3.2.1.min.js"></script>-->
    <!-- 引入3D库-->
    <script src="{% static "js/three.js" %}"></script>
    <!-- 引入控制器-->
    <script src="{% static "js/OrbitControls_alter.js" %}"></script>
    <!-- 引入动画库-->
    <script src="{% static "js/tween.min.js" %}"></script>




<script>
    //添加场景
    var scene = new THREE.Scene();
    //添加坐标轴
    scene.add(axes = new THREE.AxisHelper(100));

    //配置相机
    var camera;
    function initCamera(){
        camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,2000);
        camera.position.set(0,150,300);
//        camera.lookAt({
//            x : 0,
//            y : 1000,
//            z : 0
//        });

    }
    initCamera();

    //配置光源
    var dircLight;
    function initLight(){
        dircLight = new THREE.DirectionalLight(0xffffff);
        dircLight.position.set(300,400,200);
        scene.add(dircLight);
        scene.add(new THREE.AmbientLight(0x444444));
    }
    initLight();

    //设置渲染器
    var renderer;
    function initRenderer(){
        renderer = new THREE.WebGLRenderer({
            antialias:true//抗锯齿:true
        });
        renderer.setSize(window.innerWidth,window.innerHeight);//画布尺寸
        renderer.setClearColor('#39609B');//背景色
        document.body.appendChild(renderer.domElement);
    }
    initRenderer();

    //设置贴图
    var floorTexture;//地板贴图
    function initTexture(){
        floorTexture = THREE.ImageUtils.loadTexture('{% static "img/floor.jpg" %}', render);
        floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;//两个方向都重复
        floorTexture.repeat.set(14,10);//两个方向上的重复数
    }
    initTexture();

    //floor
    var floor;
    function initFloor(){
        var geometry = new THREE.BoxGeometry(400,2,300);
        var material = new THREE.MeshLambertMaterial({
            color:0xffffff,
            map:floorTexture
        });
        floor = new THREE.Mesh(geometry,material);
        floor.position.set(0,-1,0);
        scene.add(floor);
    }
    initFloor();

    //画机柜上的编号贴图
    function canvasTxture(str){
        var canvas = document.createElement("canvas");
        canvas.width = 50;
        canvas.height = 40;
        var ctx = canvas.getContext("2d");
        var g = ctx.createLinearGradient(0,0,50,40);
        g.addColorStop(0,"#777");
        g.addColorStop(1,"#777");
        ctx.fillStyle = g;
        ctx.fillRect(0,0,50,40);
        ctx.textBaseline='top';
        ctx.font="20px SimHei";
        ctx.fillStyle = "#00ffff";//编号颜色
        var txtWidth = ctx.measureText(str).width;
        ctx.fillText(str ,50/2-txtWidth/2,40/2-20/2);
        var texture = new THREE.Texture(canvas);
        texture.needsUpdate = true;
        return texture;
    }

    //机柜
    //构造机柜:参数x坐标,z坐标,机柜号
    function Cabient(x,z,cabNmb){
        this.x=x;
        this.z=z;
        this.y=0;
        this.number = cabNmb;

        var dk = 30;//底宽
        var dc = 40;//底长

        //设置机箱的外壳

        var texture1 = THREE.ImageUtils.loadTexture('{% static "img/rack_panel.jpg" %}', {}, render);//机箱外表贴图
        var texture3 = THREE.ImageUtils.loadTexture('{% static "img/cabz.jpg" %}', {}, render);//cabz
        var texture2 = THREE.ImageUtils.loadTexture('{% static "img/caby.jpg" %}', {}, render);//caby


        var cabGroup = new THREE.Group();
        //cabGroup的平面中心是机柜主体的平面中心
        cabGroup.position.set(this.x,this.y,this.z);
        cabGroup.name = 'cabGroup';


        var cabMatLambert = new THREE.MeshLambertMaterial({//设置朗伯材质和贴图
            color:0x8E8E8E,
            map:texture1
        });
        var cabMatBasic = new THREE.MeshBasicMaterial({//设置基础材质和贴图
            color:0x8E8E8E,
            map:texture1
        });

        var cabdGeo = new THREE.BoxGeometry(dk,2,dc);//箱主体底宽30，高2，长40
        var cabd = new THREE.Mesh(cabdGeo,cabMatBasic);
        cabd.position.set(0,1,0);

        var cabzGeo = new THREE.BoxGeometry(2,88,dc);//箱左侧，厚2，高88，长40
        var cabzMaterials = [];
        cabzMaterials.push(//push顺序：X轴正、反，Y轴正、反，Z轴正、反
            cabMatLambert,
            cabMatLambert,
            cabMatLambert,
            cabMatLambert,
            new THREE.MeshBasicMaterial({
                color:0xBEBEBE,
                map:texture2
            }),
            cabMatBasic
        );
        var cabzMat = new THREE.MeshFaceMaterial(cabzMaterials);
        var cabz = new THREE.Mesh(cabzGeo,cabzMat);
        cabz.position.set(dk/2-1,46,0);

        var cabyGeo = new THREE.BoxGeometry(2,88,dc);//箱左侧，厚2，高88，长40
        var cabyMaterials = [];
        cabyMaterials.push(
            cabMatLambert,
            cabMatBasic,
            cabMatLambert,
            cabMatLambert,
            new THREE.MeshBasicMaterial({
                color:0xBEBEBE,
                map:texture3
            }),
            cabMatBasic
        );
        var cabyMat = new THREE.MeshFaceMaterial(cabyMaterials);
        var caby = new THREE.Mesh(cabyGeo,cabyMat);
        caby.position.set(-dk/2+1,46,0);

        var cabhGeo = new THREE.BoxGeometry(dk-4,88,2);//后板宽26，高88，厚2
        var cabh = new THREE.Mesh(cabhGeo,cabMatBasic);
        cabh.position.set(0,46,0-dc/2+1);

        var cabsGeo = new THREE.BoxGeometry(dk,2,dc);
        var cabsMaterials = [];
        cabsMaterials.push(
            cabMatBasic,
            cabMatBasic,
            new THREE.MeshLambertMaterial({
                color:0x8E8E8E,
                map:canvasTxture(this.number)//canvas贴图
            }),
            cabMatLambert,
            cabMatLambert,
            cabMatLambert
        );
        var cabsMat = new THREE.MeshFaceMaterial(cabsMaterials);
        var cabs = new THREE.Mesh(cabsGeo,cabsMat);
        cabs.position.set(0,91,0);
        cabs.name = 'cabs';

        cabGroup.add(cabd,cabz,caby,cabh,cabs);//cabGroup不包括机箱门

        //设置机箱门
        var menGroup = new THREE.Group();
        menGroup.position.set(this.x+15,this.y,this.z+20);
        menGroup.name = this.number;//机箱门的名字为输入的编号

        var menGeo = new THREE.BoxGeometry(dk,92,1);//机箱们宽，高，厚
        var mMaterials = [];
        mMaterials.push(
            new THREE.MeshLambertMaterial({color:0x999999}),
            new THREE.MeshLambertMaterial({color:0x999999}),
            new THREE.MeshLambertMaterial({color:0x999999}),
            new THREE.MeshLambertMaterial({color:0x999999}),
            new THREE.MeshLambertMaterial({
                map:THREE.ImageUtils.loadTexture(
                    '{% static "img/rack_front_door.jpg" %}',
                    {},
                    render
                ),
                overdraw:true
            }),
            new THREE.MeshBasicMaterial({
                map:THREE.ImageUtils.loadTexture(
                    '{% static "img/rack_door_back.jpg" %}',
                    {},
                    render
                ),
                overdraw:true
            })
        );

        var menMat = new THREE.MeshFaceMaterial(mMaterials);
        var men = new THREE.Mesh(menGeo,menMat);
        men.name='men';
        men.position.set(-dk/2,46,.5);
        menGroup.add(men);

        scene.add(cabGroup,menGroup);

    }

    //构造服务器。参数：所属机柜（如cab1）,高度坐标
    function Server(obj,h){
        this.x = obj.x;
        this.z = obj.z;
        this.y = 0;
        this.h = h;

        var serv2Group = new THREE.Group();
        serv2Group.name = 'serverGroup';
        serv2Group.position.set(this.x ,this.y,this.z);

        // 确保设置原始位置
        serv2Group.userData = {
            originalZ: this.z
        };

        //两层的服务器
        var servTexture = THREE.ImageUtils.loadTexture('{% static "img/rack_inside.jpg" %}', {}, render);
        var serv2Geo = new THREE.BoxGeometry(24,3.5,36);//这里服务器的尺寸要跟机箱尺寸对应好
        var servMat = new THREE.MeshBasicMaterial({
            color:0x9AC0CD,
            map:servTexture
        });
        var server2 = new THREE.Mesh(serv2Geo,servMat);//服务器主体
        server2.name = 'serverBody';
        server2.position.set(0,this.h,2);

        var server2mGeo = new THREE.BoxGeometry(26.4,4,0.2);//服务器面板尺寸
        var smb2Materials = [];
        smb2Materials.push(
            new THREE.MeshBasicMaterial({color:0xffffff}),
            new THREE.MeshBasicMaterial({color:0xffffff}),
            new THREE.MeshBasicMaterial({color:0xffffff}),
            new THREE.MeshBasicMaterial({color:0xffffff}),
            new THREE.MeshBasicMaterial({
                map:THREE.ImageUtils.loadTexture(
                    '{% static "img/server2.jpg" %}',
                    {},
                    render
                ),
                overdraw:true
            }),
            new THREE.MeshBasicMaterial({color:0xffffff})
        );
        var server2mMat = new THREE.MeshFaceMaterial(smb2Materials);//服务器面板材质
        var server2face = new THREE.Mesh(server2mGeo,server2mMat );
        server2face.name= 'ctr2';
        server2face.position.set(0,this.h,36/2+0.2/2+2);
        serv2Group.add(server2,server2face);


        scene.add(serv2Group);

        console.log('Server created:', {
            group: serv2Group.name,
            position: serv2Group.position.toArray(),
            children: [server2.name, server2face.name]
        });
    }

    // 往机柜里加个构造交换机
    function Switchboard(obj,h){
        this.x = obj.x;
        this.z = obj.z;
        this.h = h;

        var switchGroup = new THREE.Group();
        switchGroup.position.set(this.x ,0,this.z);
        var switchTexture = THREE.ImageUtils.loadTexture('{% static "img/rack_inside.jpg" %}', {}, render);
        var switchGeo = new THREE.BoxGeometry(24,11.5,36);//交换机主体尺寸，宽厚长，要跟机箱对应
        var switchMat = new THREE.MeshBasicMaterial({
            color:0x9AC0CD,
            map:switchTexture
        });
        var switchBody = new THREE.Mesh(switchGeo,switchMat);
        switchBody.position.set(0,this.h,2);

        var switchmGeo = new THREE.BoxGeometry(26.4,12,0.2);//交换机面板尺寸
        var switchmMat = new THREE.MeshBasicMaterial({//交换机面板材质
            color:0xffffff
        });
        var switchfMaterials = [];
        switchfMaterials.push(
            switchmMat,
            switchmMat,
            switchmMat,
            switchmMat,
            new THREE.MeshBasicMaterial({
                map:THREE.ImageUtils.loadTexture(
                    '{% static "img/switchboard.jpg" %}',
                    {},
                    render
                ),
                overdraw:true
            }),
            switchmMat

        );
        var switchfMat = new THREE.MeshFaceMaterial(switchfMaterials);//交换机面板材质
        var switchface = new THREE.Mesh(switchmGeo,switchfMat);
        switchface.position.set(0,this.h,36/2+0.2/2+2);


        switchGroup.add(switchBody,switchface);
        scene.add(switchGroup);
    }

    document.addEventListener('dblclick', function(event) {
        event.preventDefault();
        
        var rect = renderer.domElement.getBoundingClientRect();
        var mouse = new THREE.Vector2();
        mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
        mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
        
        var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
        vector.unproject(camera);
        var raycaster = new THREE.Raycaster(
            camera.position,
            vector.sub(camera.position).normalize()
        );
        
        var clickableObjects = [];
        scene.traverse(function(object) {
            if (object instanceof THREE.Mesh) {
                clickableObjects.push(object);
            }
        });
        
        var intersects = raycaster.intersectObjects(clickableObjects);
        
        if (intersects.length > 0) {
            var clickedObject = intersects[0].object;
            console.log('Clicked:', clickedObject.name);
            
            if (clickedObject.name === 'ctr2' || clickedObject.name === 'serverBody') {
                var serverGroup = clickedObject;
                while (serverGroup && serverGroup.name !== 'serverGroup') {
                    serverGroup = serverGroup.parent;
                }
                
                if (serverGroup) {
                    var currentZ = serverGroup.position.z;
                    var baseZ = serverGroup.userData.originalZ;
                    var isExtended = Math.abs(currentZ - baseZ - 20) < 0.1;
                    var targetZ = isExtended ? baseZ : baseZ + 20;
                    
                    new TWEEN.Tween(serverGroup.position)
                        .to({ z: targetZ }, 500)
                        .easing(TWEEN.Easing.Quadratic.Out)
                        .start();
                }
            }
            
            if (clickedObject.name === 'men') {
                var doorGroup = clickedObject.parent;
                var targetRotation = doorGroup.rotation.y === 0 ? Math.PI * 0.6 : 0;
                
                new TWEEN.Tween(doorGroup.rotation)
                    .to({ y: targetRotation }, 500)
                    .easing(TWEEN.Easing.Quadratic.Out)
                    .start();
            }
        }
    }, false);


    //视角控制器
    var controls;
    function ctr(){
        controls = new THREE.OrbitControls(camera);
        controls.addEventListener('change',render);
        //相机到原点的最远距离
        controls.maxDistance = 2000;
    }
    ctr();

    function render() {
        renderer.render(scene, camera);
    }

    function animate() {
        requestAnimationFrame(animate);
        TWEEN.update();
        controls.update();
        render();
    }
    animate();


    function onResize() {
        // aspect表示屏幕长宽比
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    }
    // 浏览器变化时画布自适应
    window.addEventListener('resize', onResize, false);

    // 添加从后端获取机柜信息并创建机柜的函数
    function createCabinetsFromBackend() {
        fetch('/api/cabinets/')
            .then(response => response.json())
            .then(cabinets => {
                const CABINET_SPACING = 50;
                let currentX = 0;
                
                cabinets.forEach((cabinet, index) => {
                    let x = currentX + (index * CABINET_SPACING);
                    
                    // 使用后端提供的编号创建机柜
                    let cab = new Cabient(
                        x,
                        cabinet.position_z,
                        cabinet.number  // 使用后端提供的机柜编号
                    );
                    
                    // 如果有服务器信息，创建服务器
                    if (cabinet.servers) {
                        cabinet.servers.forEach(server => {
                            new Server(cab, server.height);
                        });
                    }
                    
                    // 如果有交换机信息，创建交换机
                    if (cabinet.switchboards) {
                        cabinet.switchboards.forEach(switchboard => {
                            new Switchboard(cab, switchboard.height);
                        });
                    }
                });
            })
            .catch(error => {
                console.error('获取机柜信息失败:', error);
            });
    }

    // 页面加载完成后调用创建函数
    createCabinetsFromBackend();

    // 添加设备相关的JavaScript代码
    document.addEventListener('DOMContentLoaded', function() {
        const addDeviceIcon = document.querySelector('.add-device-icon');
        const deviceModal = document.querySelector('.device-modal');
        const deviceTypeSelect = document.getElementById('deviceType');
        const deviceListSelect = document.getElementById('deviceList');
        const cabinetListSelect = document.getElementById('cabinetList');
        const uPositionSelect = document.getElementById('uPosition');
        const saveBtn = document.querySelector('.save-btn');
        const cancelBtn = document.querySelector('.cancel-btn');
        
        // 显示设备选择窗口
        addDeviceIcon.addEventListener('click', function() {
            deviceModal.style.display = 'block';
            loadDeviceTypes();
            loadCabinets();
        });
        
        //加载设备类型
        function loadDeviceTypes() {
            fetch('/api/device-types/')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // 处理设备类型数据
                        const dropdown = document.getElementById('deviceType');
                        dropdown.innerHTML = '<option value="">请选择设备类型</option>';
                        
                        // 确保 data.data 是数组并且存在
                        const deviceTypes = Array.isArray(data.data) ? data.data : 
                                          (data.data?.asset_categories || []);
                        deviceTypes.forEach(item => {
                            const option = document.createElement('option');
                            option.value = item.id;
                            option.textContent = item.name;
                            dropdown.appendChild(option);
                        });
                        
                        // 调试输出

                        console.log('下拉菜单元素:', dropdown);
                        console.log('选项数量:', dropdown.options.length);
                        
                        // 确保select元素可以点击
                        dropdown.style.pointerEvents = 'auto';
                        dropdown.style.cursor = 'pointer';
                    } else {
                        console.error('获取数据失败：', data.message);
                    }
                })
                .catch(error => {
                    console.error('请求失败：', error);
                    const dropdown = document.getElementById('deviceType');
                    dropdown.innerHTML = '<option value="">加载失败，请刷新重试</option>';
                });
        }

        // 设备类型变化时加载对应的设备列表
        document.getElementById('deviceType').addEventListener('change', function() {
            const typeId = this.value;
            const deviceListSelect = document.getElementById('deviceList');
            
            if (typeId) {
                // 修正 API 路径，确保以 / 开头
                fetch(`/api/devices/type/${typeId}/`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(response => {
                        if (response.status === 'success') {
                            deviceListSelect.innerHTML = '<option value="">请选择资产</option>';
                            
                            response.data.forEach(asset => {
                                const option = document.createElement('option');
                                option.value = asset.id;
                                // 显示更多资产信息
                                option.textContent = `${asset.name} (${asset.asset_number || '无编号'})`;
                                // 添加悬停提示
                                option.title = `
                                    状态: ${asset.status}
                                    上架日期: ${asset.up_rack_time || '未知'}
                                    负责人: ${asset.responsible_person || '未指定'}
                                    ${asset.description ? '\n描述: ' + asset.description : ''}
                                `;
                                deviceListSelect.appendChild(option);
                            });
                            
                            // 启用下拉菜单
                            deviceListSelect.disabled = false;
                            

                        } else {
                            throw new Error(response.message || '加载资产列表失败');
                        }
                    })
                    .catch(error => {
                        console.error('加载资产列表失败:', error);
                        deviceListSelect.innerHTML = '<option value="">加载失败，请重试</option>';
                        deviceListSelect.disabled = true;
                    });
            } else {
                // 未选择类型时重置
                deviceListSelect.innerHTML = '<option value="">请先选择资产类型</option>';
                deviceListSelect.disabled = true;
            }
        });
        
        // 加载机柜列表
        function loadCabinets() {
            fetch('/api/cabinets/')
                .then(response => response.json())
                .then(data => {
                    cabinetListSelect.innerHTML = '<option value="">请选择机柜</option>';
                    data.forEach(cabinet => {
                        cabinetListSelect.innerHTML += `<option value="${cabinet.id}">${cabinet.number}</option>`;
                    });
                });
        }
        
        // 根据选择的机柜加载可用U位
        cabinetListSelect.addEventListener('change', function() {
            const cabinetId = this.value;
            if (cabinetId) {
                fetch(`/api/cabinet/free-units/${cabinetId}/`)
                    .then(response => response.json())
                    .then(data => {
                        uPositionSelect.innerHTML = '<option value="">请选择U位</option>';
                        data.forEach(position => {
                            uPositionSelect.innerHTML += `<option value="${position}">${position}U</option>`;
                        });
                    });
            }
        });
        
        // 保存按钮事件
        saveBtn.addEventListener('click', function() {
            const deviceId = deviceListSelect.value;
            const cabinetId = cabinetListSelect.value;
            const position = uPositionSelect.value;
            
            if (!deviceId || !cabinetId || !position) {
                alert('请填写完整信息');
                return;
            }
            
            fetch('/api/add_device_to_cabinet', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    device_id: deviceId,
                    cabinet_id: cabinetId,
                    position: position
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('添加成功');
                    deviceModal.style.display = 'none';
                    // 刷新3D视图
                    createCabinetsFromBackend();
                } else {
                    alert('添加失败：' + data.message);
                }
            });
        });
        
        // 取消按钮事件
        cancelBtn.addEventListener('click', function() {
            deviceModal.style.display = 'none';
        });
        
        // 获取CSRF Token的辅助函数
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    });

    // 防止Three.js画布事件干扰下拉菜单
    document.querySelector('.device-modal').addEventListener('mousedown', function(e) {
        e.stopPropagation();
    });

    document.querySelector('.device-modal').addEventListener('click', function(e) {
        e.stopPropagation();
    });

    // 确保select元素可以接收事件
    const selects = document.querySelectorAll('.device-modal select');
    selects.forEach(select => {
        select.addEventListener('mousedown', function(e) {
            e.stopPropagation();
        });
        
        select.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    });
</script>


{% endblock %}